﻿using CefSharp;
using CefSharp.DevTools.Network;
using CefSharp.WinForms;
using System;
using System.Drawing;
using System.IO;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using static mytools.CEFJSBridge;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Timer = System.Windows.Forms.Timer;

namespace mytools
{
    public partial class Form1 : Form
    {
        private NotifyIcon notifyIcon;
        private ContextMenuStrip contextMenu;
        public static Form window2;
        private string previousClipboardText;
        public ChromiumWebBrowser browser { get; set; }
        public ChromiumWebBrowser browser2 { get; set; }
        private float initialZoomFactor;

        string filePath = "C:\\Users\\mima\\Desktop\\Output\\copy.txt";

        private int maxItemCount = 20;
        private int currentFixedCount = 0;//当前固定的条目数
        public Form1()
        {
            InitializeComponent();
            this.Load += MainForm_Load; // 将 MainForm_Load 事件与窗体的 Load 事件关联
            //Double scale = Dpi.GetScreenScalingFactor();
            //this.ClientSize = new System.Drawing.Size((int)(800 * scale), (int)(500 * scale));//把客户端等比例缩放
            this.FormBorderStyle = FormBorderStyle.FixedSingle;

            //禁止修改窗口大小
            this.MaximizeBox = false;//禁止最大化
            //this.MinimizeBox = false;//禁止最小化
            //this.ControlBox = false;//禁止右上角关闭按钮

            // 创建 CefSharp 设置对象
            CefSettings settings = new CefSettings();
            //settings.CefCommandLineArgs.Add("disable-web-security", "1");//允许跨域请求

            // 将日志级别设置为禁用控制台输出
            settings.LogSeverity = LogSeverity.Disable;

            Cef.Initialize(settings);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized; // 在窗体加载时将其最小化
            InitializeNotifyIcon();
            InitializeClipboardPolling();
            //Ctrl+Space
            HotKey.RegisterHotKey(Handle, 100, HotKey.KeyModifiers.Ctrl, Keys.Space);
            HotKey.RegisterHotKey(Handle, 200, HotKey.KeyModifiers.Ctrl, Keys.D1);
            HotKey.RegisterHotKey(Handle, 300, HotKey.KeyModifiers.Ctrl, Keys.D2);
            HotKey.RegisterHotKey(Handle, 400, HotKey.KeyModifiers.Ctrl, Keys.D3);
        }

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool AddClipboardFormatListener(IntPtr hwnd);

        private void InitializeClipboardPolling()
        {
            // 使用定时器每隔一段时间检查剪贴板内容的变化
            Timer clipboardTimer = new Timer();
            clipboardTimer.Interval = 500; // 设置定时器间隔为1秒
            clipboardTimer.Tick += ClipboardTimer_Tick;
            clipboardTimer.Start();
        }

        private void ClipboardTimer_Tick(object sender, EventArgs e)
        {
            string base64String = "";
            Image clipboardImage = null;
            string clipboardText = "";
            if (Clipboard.ContainsImage())
            {
                clipboardImage = Clipboard.GetImage();
                if (clipboardImage != null)
                {
                    // 将图片转换为 Base64 字符串
                    base64String = Common.ImageToBase64(clipboardImage);
                    base64String = $"data:image/png;base64,{base64String}";
                    if (Common.CalculateMD5(base64String) != previousClipboardText)
                    {
                        string remark = "";
                        Console.WriteLine("解析");
                        //尝试解析二维码
                        string decodedText = Common.DecodeQRCode(clipboardImage);

                        if (!string.IsNullOrEmpty(decodedText))
                        {
                            remark = decodedText;
                            Console.WriteLine("Decoded QR Code: " + decodedText);
                            // 在这里使用解析出的链接进行后续操作
                        }
                        string script = $"jsAddItem(`{base64String}`, `{remark}`, `1`);";
                        //Console.WriteLine(script);
                        browser2.ExecuteScriptAsync(script);
                        previousClipboardText = Common.CalculateMD5(base64String);
                    }
                }
            }
            else if (Clipboard.ContainsText())
            {
                clipboardText = Clipboard.GetText();
                if (!string.IsNullOrEmpty(clipboardText) && clipboardText != previousClipboardText)
                {
                    if (browser2.IsBrowserInitialized)
                    {
                        string remark = "";
                        //if (Common.IsTimestamp(clipboardText))//时间戳
                        //{
                        //    // 输出时间戳
                        //    DateTime dt = Common.UnixTimeStampToDateTime(double.Parse(clipboardText));
                        //    remark = dt.ToString("yyyy-MM-dd HH:mm:ss");
                        //}
                        //写入文件
                        try
                        {
                            Console.WriteLine(File.Exists(filePath));
                            // 检查文件是否存在
                            if (File.Exists(filePath))
                            {
                                // 将修改后的内容覆盖保存回文件
                                File.WriteAllText(filePath, clipboardText);
                                Console.WriteLine("File content has been updated and saved.");
                            }
                        }
                        catch (FileNotFoundException)
                        {
                            Console.WriteLine("File not found.");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("An error occurred: " + ex.Message);
                        }

                        string script = $"jsAddItem(`{clipboardText}`, `{remark}`);";
                        Console.WriteLine(script);
                        browser2.ExecuteScriptAsync(script);
                    }
                    previousClipboardText = clipboardText;
                }
            }
        }

        private void InitializeNotifyIcon()
        {
            notifyIcon = new NotifyIcon();
            contextMenu = new ContextMenuStrip();
            ToolStripMenuItem showWindowItem = new ToolStripMenuItem("显示窗口");
            showWindowItem.Click += ShowWindowItem_Click;
            contextMenu.Items.Add(showWindowItem);

            // 添加退出菜单项
            ToolStripMenuItem exitItem = new ToolStripMenuItem("退出");
            exitItem.Click += ExitItem_Click;
            contextMenu.Items.Add(exitItem);

            notifyIcon.Icon = SystemIcons.Application;
            notifyIcon.ContextMenuStrip = contextMenu;
            notifyIcon.Visible = true;
            notifyIcon.DoubleClick += NotifyIcon_DoubleClick;

            /// 创建窗口2
            window2 = new Form();
            window2.FormClosing += Window_FormClosing;
            window2.FormBorderStyle = FormBorderStyle.FixedToolWindow;
            //window2.WindowState = FormWindowState.Minimized;
            window2.ClientSize = new System.Drawing.Size(934, 340);
            // 计算窗口显示在屏幕中间的位置
            int screenWidth = Screen.PrimaryScreen.WorkingArea.Width;
            int screenHeight = Screen.PrimaryScreen.WorkingArea.Height;
            int windowWidth = window2.Width;
            int windowHeight = window2.Height;
            int x = (screenWidth - windowWidth) / 2;
            int y = (screenHeight - windowHeight) / 2;

            window2.StartPosition = FormStartPosition.Manual;
            window2.Location = new Point(x, y); // 设置窗口位置
            window2.WindowState = FormWindowState.Normal;
            window2.Show();

            //browser = new ChromiumWebBrowser("https://www.mimaapp.com");
            // 设置 CefSharpSettings.WcfEnabled 为 true
            browser2 = new ChromiumWebBrowser();

            browser2.Dock = DockStyle.Fill;
            // 注册 IsBrowserInitializedChanged 事件
            browser2.IsBrowserInitializedChanged += OnBrowserInitializedChanged;
            browser2.MenuHandler = new CustomContextMenuHandler();
            //browser2.FrameLoadEnd += OnBrowserFrameLoadEnd;
            

            string htmlPath;
            // 加载本地的 HTML 文件
            htmlPath = Path.Combine(Application.StartupPath, "tool.html");

            browser2.Load(htmlPath);

            var jsBridge = new CEFJSBridge(this);

            //browser.RegisterJsObject("cefjsbridge", jsBridge);
            CefSharpSettings.WcfEnabled = true;
             browser2.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true; // 在创建浏览器之前设置属性
            browser2.JavascriptObjectRepository.Register("cefjsbridge", jsBridge, isAsync: false, options: BindingOptions.DefaultBinder);
            window2.Controls.Add(browser2);

            this.WindowState = FormWindowState.Minimized; // 主窗口默认最小化
        }

        private static void Window_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (window2.WindowState == FormWindowState.Normal)
            {
                e.Cancel = true; // 取消关闭操作
                window2.WindowState = FormWindowState.Minimized;//改为最小化
            }
        }

        private void OnBrowserInitializedChanged(object sender, EventArgs e)
        {
            // 检查 CEF 控件是否已经初始化完成
            if (browser2.IsBrowserInitialized)
            {
                // 获取浏览器主机对象
                var host = browser2.GetBrowser().GetHost();

                // 打开开发者工具窗口
                //host.ShowDevTools();

                // 在控制台中输出一条消息
                browser2.GetMainFrame().ExecuteJavaScriptAsync("console.log('Hello, world!');");
            }
        }

        private void ExitItem_Click(object sender, EventArgs e)
        {
            window2.Close();
            notifyIcon.Dispose(); // 删除托盘图标
        }
        private void ShowWindowItem_Click(object sender, EventArgs e)
        {
            ShowWindow2();
        }

        private void NotifyIcon_DoubleClick(object sender, EventArgs e)
        {
            ShowWindow2();
        }

        private void ShowWindow2()
        {
            Console.WriteLine(window2.WindowState);
            window2.WindowState = FormWindowState.Minimized;
            window2.WindowState = FormWindowState.Normal;
            //if (window2.WindowState == FormWindowState.Minimized)
            //{
            //    window2.WindowState = FormWindowState.Normal;
            //}
            //else
            //{
            //    window2.WindowState = FormWindowState.Minimized;
            //    window2.WindowState = FormWindowState.Normal;
            //}
        }


        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;
            //按快捷键 
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    switch (m.WParam.ToInt32())
                    {
                        case 100:    //按下的是Ctrl+Space
                            ShowWindow2();
                            break;
                        case 200:    //按下的是Ctrl+1
                            Common.SwitchToProcessWindow("wechat");
                            break;
                        case 300:    //按下的是Ctrl+2
                            Common.SwitchToProcessWindow("chrome");
                            break;
                        case 400:    //按下的是Ctrl+3
                            Common.SwitchToProcessWindow("navicat");
                            break;
                    }
                    break;
            }
            base.WndProc(ref m);
        }

        protected override void Dispose(bool disposing)
        {
            HotKey.UnregisterHotKey(Handle, 100);
            HotKey.UnregisterHotKey(Handle, 200);
            HotKey.UnregisterHotKey(Handle, 300);
            HotKey.UnregisterHotKey(Handle, 400);
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void OnBrowserFrameLoadEnd(object sender, FrameLoadEndEventArgs args)
        {
            if (args.Frame.IsMain)
            {
                args
                    .Browser
                    .MainFrame
                    .ExecuteJavaScriptAsync(
                    "document.body.style.overflow = 'hidden'");
            }
        }
    }

    public class SubItemMouseClickEventArgs : EventArgs
    {
        public ListViewItem Item { get; }
        public ListViewItem.ListViewSubItem SubItem { get; }
        public int X { get; }
        public int Y { get; }

        public SubItemMouseClickEventArgs(ListViewItem item, ListViewItem.ListViewSubItem subItem, int x, int y)
        {
            Item = item;
            SubItem = subItem;
            X = x;
            Y = y;
        }
    }

    internal class CustomContextMenuHandler : IContextMenuHandler
    {
        private const int ShowDevTools = 26501;
        private const int CloseDevTools = 26502;
        public void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
        {
            // 禁用右键菜单显示
            model.Clear();

            //Removing existing menu item
            //bool removed = model.Remove(CefMenuCommand.ViewSource); // Remove "View Source" option

            //Add new custom menu items
            model.AddItem((CefMenuCommand)ShowDevTools, "Show DevTools");
            model.AddItem((CefMenuCommand)CloseDevTools, "Close DevTools");

        }

        bool IContextMenuHandler.OnContextMenuCommand(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
        {
            if ((int)commandId == ShowDevTools)
            {
                browser.ShowDevTools();
            }
            if ((int)commandId == CloseDevTools)
            {
                browser.CloseDevTools();
            }
            return false;
        }

        void IContextMenuHandler.OnContextMenuDismissed(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame)
        {

        }

        bool IContextMenuHandler.RunContextMenu(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback)
        {
            return false;
        }

    }
}
